# 翻转二叉树: https://leetcode-cn.com/problems/invert-binary-tree/submissions/

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        """
            第一种思路，使用深度优先遍历， 后序实现
        """
        def dfs(node):
            if not node:
                return None
            
            left = dfs(node.left)
            right = dfs(node.right)

            if left or right:
                node.right = left
                node.left = right
            
            return node
        

        return dfs(root)


from collections import deque
class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        """
            广度优先层序遍历
        """
        if not root:
            return root
            
        d = deque()
        d.append(root)
        while d:
            node = d.popleft()        
            if node.left: d.append(node.left)
            if node.right: d.append(node.right)

            left = node.left
            right = node.right
            if left or right:
                node.left = right
                node.right = left

        return root